<template>
  <div class="toolbarContainer" :class="{ isDark: isDark }">
    <div class="toolbar" ref="toolbarRef">
       <div class="toolbarBlock">
        <!-- 新增保存草稿按钮 -->
        <div class="toolbarBtn" @click="handleBackToList">
          <span class="icon iconfont iconhoutui-shi"></span>
          <span class="text">{{ $t('toolbar.backList') }}</span>
        </div>
      </div>
      <!-- 节点操作 -->
      <div class="toolbarBlock">
        <ToolbarNodeBtnList :list="horizontalList"></ToolbarNodeBtnList>
        <!-- 更多 -->
        <el-popover
          v-model="popoverShow"
          placement="bottom-end"
          width="120"
          trigger="hover"
          v-if="showMoreBtn"
          :style="{ marginLeft: horizontalList.length > 0 ? '20px' : 0 }"
        >
          <ToolbarNodeBtnList
            dir="v"
            :list="verticalList"
            @click.native="popoverShow = false"
          ></ToolbarNodeBtnList>
          <div slot="reference" class="toolbarBtn">
            <span class="icon iconfont icongongshi"></span>
            <span class="text">{{ $t('toolbar.more') }}</span>
          </div>
        </el-popover>
      </div>
      <!-- 导出 -->
      <div class="toolbarBlock">
        <div class="toolbarBtn" @click="openDirectory" v-if="!isMobile">
          <span class="icon iconfont icondakai"></span>
          <span class="text">{{ $t('toolbar.directory') }}</span>
        </div>
        <el-tooltip
          effect="dark"
          :content="$t('toolbar.newFileTip')"
          placement="bottom"
          v-if="!isMobile"
        >
          <div class="toolbarBtn" @click="createNewLocalFile">
            <span class="icon iconfont iconxinjian"></span>
            <span class="text">{{ $t('toolbar.newFile') }}</span>
          </div>
        </el-tooltip>
        <el-tooltip
          effect="dark"
          :content="$t('toolbar.openFileTip')"
          placement="bottom"
          v-if="!isMobile"
        >
          <div class="toolbarBtn" @click="openLocalFile">
            <span class="icon iconfont iconwenjian1"></span>
            <span class="text">{{ $t('toolbar.openFile') }}</span>
          </div>
        </el-tooltip>
        <div class="toolbarBtn" @click="saveLocalFile" v-if="!isMobile">
          <span class="icon iconfont iconlingcunwei"></span>
          <span class="text">{{ $t('toolbar.saveAs') }}</span>
        </div>
        <div class="toolbarBtn" @click="handleShowImport">
          <span class="icon iconfont icondaoru"></span>
          <span class="text">{{ $t('toolbar.import') }}</span>
        </div>
        <!-- 在保存按钮后面添加保存草稿按钮 -->
        <!-- 新增保存按钮 -->
        <div class="toolbarBtn" @click="handleShowSave">
          <span class="icon iconfont iconlingcunwei"></span>
          <span class="text">{{ $t('toolbar.save') }}</span>
        </div>
        <!-- 新增保存草稿按钮 -->
        <div class="toolbarBtn" @click="handleShowSaveDraft">
          <span class="icon iconfont iconlingcunwei"></span>
          <span class="text">{{ $t('toolbar.saveDraft') }}</span>
        </div>
        <div
          class="toolbarBtn"
          @click="handleShowExport"
          style="margin-right: 0;"
        >
          <span class="icon iconfont iconexport"></span>
          <span class="text">{{ $t('toolbar.export') }}</span>
        </div>
        <!-- 本地文件-->
        <div
          class="fileTreeBox"
          v-if="fileTreeVisible"
          :class="{ expand: fileTreeExpand }"
        >
          <div class="fileTreeToolbar">
            <div class="fileTreeName">
              {{ rootDirName ? '/' + rootDirName : '' }}
            </div>
            <div class="fileTreeActionList">
              <div
                class="btn"
                :class="[
                  fileTreeExpand ? 'el-icon-arrow-up' : 'el-icon-arrow-down'
                ]"
                @click="fileTreeExpand = !fileTreeExpand"
              ></div>
              <div
                class="btn el-icon-close"
                @click="fileTreeVisible = false"
              ></div>
            </div>
          </div>
          <div class="fileTreeWrap">
            <el-tree
              :props="fileTreeProps"
              :load="loadFileTreeNode"
              :expand-on-click-node="false"
              node-key="id"
              lazy
            >
              <span class="customTreeNode" slot-scope="{ node, data }">
                <div class="treeNodeInfo">
                  <span
                    class="treeNodeIcon iconfont"
                    :class="[
                      data.type === 'file' ? 'iconwenjian' : 'icondakai'
                    ]"
                  ></span>
                  <span class="treeNodeName">{{ node.label }}</span>
                </div>
                <div class="treeNodeBtnList" v-if="data.type === 'file'">
                  <el-button
                    type="text"
                    size="small"
                    v-if="data.enableEdit"
                    @click="editLocalFile(data)"
                    >编辑</el-button
                  >
                  <el-button
                    type="text"
                    size="small"
                    v-else
                    @click="importLocalFile(data)"
                    >导入</el-button
                  >
                  
                </div>
              </span>
            </el-tree>
          </div>
        </div>
      </div>
    </div>
    <NodeImage></NodeImage>
    <NodeHyperlink></NodeHyperlink>
    <NodeIcon></NodeIcon>
    <NodeNote></NodeNote>
    <NodeTag></NodeTag>
    <Export></Export>
    <Import ref="ImportRef"></Import>
    
    <!-- 新增保存对话框 -->
    <el-dialog
      :title="isDraft ? '保存草稿' : '保存图谱'"
      v-model="saveDialogVisible"
      width="400px"
      :class="{ isDark: isDark }"
    >
      <el-form :model="saveForm" label-width="80px">
        <el-form-item label="图谱名称">
          <el-input v-model="saveForm.mapName" placeholder="请输入图谱名称"></el-input>
        </el-form-item>
        <el-form-item label="图谱权限">
          <el-select v-model="saveForm.permission" style="width: 100%">
            <el-option label="个人" value="个人"></el-option>
            <el-option label="小组" value="小组"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="预警邮箱">
          <el-input 
            v-model="saveForm.alertEmails" 
            placeholder="输入邮箱, 多个值用分号分隔"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleSaveCancel">取消</el-button>
          <el-button type="primary" @click="handleSaveConfirm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, watch, nextTick, onMounted,onBeforeUnmount, onUnmounted, reactive } from 'vue'
import { storeToRefs } from 'pinia'
import { useI18n } from 'vue-i18n'
import { useRouter } from 'vue-router' // 新增：导入useRouter
import { useMainStore } from '@/stores'
import { useEventBus } from '@/hooks'
import { ElNotification, ElMessage, ElLoading } from 'element-plus'
import NodeImage from './NodeImage.vue'
import NodeHyperlink from './NodeHyperlink.vue'
import NodeIcon from './NodeIcon.vue'
import NodeNote from './NodeNote.vue'
import NodeTag from './NodeTag.vue'
import Export from './Export.vue'
import Import from './Import.vue'
import exampleData from 'simple-mind-map/example/exampleData'
import { getData } from '@/api'
import ToolbarNodeBtnList from './ToolbarNodeBtnList.vue'
import { throttle, isMobile } from 'simple-mind-map/src/utils/index'

// 定义props
const props = defineProps({
  mindMap: {
    type: Object,
    required: true
  }
})

// 定义emit
const emit = defineEmits(['showImport', 'showExport'])

// 工具�?
let fileHandle = null
const defaultBtnList = [
  'back',
  'forward',
  'painter',
  'siblingNode',
  'childNode',
  'deleteNode',
  'image',
  'icon',
  // 'link',
  'note',
  'tag',
  'file',
  'freeTextBox', // 新增自由文本框按钮
  // 'summary',
  // 'associativeLine',
  // 'formula',
  // 'attachment',
  // 'outerFrame',
  'annotation',
  // 'ai'
]

// 响应式数�?
const toolbarRef = ref(null)
const horizontalList = ref([])
const verticalList = ref([])
const showMoreBtn = ref(true)
const popoverShow = ref(false)
const fileTreeProps = ref({
  label: 'name',
  children: 'children',
  isLeaf: 'leaf'
})
const fileTreeVisible = ref(false)
const rootDirName = ref('')
const fileTreeExpand = ref(true)
const waitingWriteToLocalFile = ref(false)
const isFullDataFile = ref(false)
const timer = ref(null)
const computeToolbarShowThrottle = ref(null)

// 使用store和i18n
const store = useMainStore()
const { isHandleLocalFile, localConfig } = storeToRefs(store)
const { t } = useI18n()
const { $on, $off, $emit, $once } = useEventBus()

// 计算属性
const isDark = computed(() => localConfig.value.isDark)
const openNodeRichText = computed(() => localConfig.value.openNodeRichText)
const enableAi = computed(() => localConfig.value.enableAi)

// 计算属�?
const btnLit = computed(() => {
  let res = [...defaultBtnList]
  if (!openNodeRichText.value) {
    res = res.filter(item => {
      return item !== 'formula'
    })
  }
  if (!enableAi.value) {
    res = res.filter(item => {
      return item !== 'ai'
    })
  }
  return res
})

// 导入导出
const handleShowImport = () => {
  $emit('showImport')
}
const saveDialogVisible = ref(false)
// 新增保存表单数据
const saveForm = reactive({
  mapName: '',
  permission: '个人',
  alertEmails: ''
})
// 新增保存方法
const handleShowSave = () => {
  saveDialogVisible.value = true
}

// 新增保存草稿相关状态
const isDraft = ref(false)

// 新增保存草稿方法
const handleShowSaveDraft = () => {
  isDraft.value = true
  saveDialogVisible.value = true
}

// 修改handleSaveConfirm方法，添加草稿标识
const handleSaveConfirm = () => {
  // 获取所有节点信息
  const mindMapData = props.mindMap.getData()
  
  // 获取自由节点数据
  const getFreeTextBoxData = () => {
    const freeTextBoxData = []
    const svg = document.querySelector('#mindMapContainer svg')
    if (!svg) return freeTextBoxData
    
    const freeTextBoxGroups = svg.querySelectorAll('.free-text-box')
    freeTextBoxGroups.forEach(group => {
      const textElement = group.querySelector('text')
      const bgRect = group.querySelector('rect')
      const transform = group.getAttribute('transform')
      
      if (textElement && bgRect && transform) {
        // 提取位置信息
        const transformMatch = transform.match(/translate\(([^,]+),([^)]+)\)/)
        if (transformMatch) {
          const x = parseFloat(transformMatch[1])
          const y = parseFloat(transformMatch[2])
          
          // 获取文本内容
          let textContent = ''
          const tspans = textElement.querySelectorAll('tspan')
          if (tspans.length > 0) {
            textContent = Array.from(tspans).map(tspan => tspan.textContent).join('\n')
          } else {
            textContent = textElement.textContent
          }
          
          freeTextBoxData.push({
            id: group.getAttribute('data-id'),
            text: textContent,
            x: x,
            y: y,
            width: parseFloat(bgRect.getAttribute('width')),
            height: parseFloat(bgRect.getAttribute('height'))
          })
        }
      }
    })
    
    return freeTextBoxData
  }
  
  const freeTextBoxData = getFreeTextBoxData()
  
  // 输出所有节点信息、自由节点信息和表单数据（包含草稿标识）
  console.log('思维导图节点信息:', mindMapData)
  console.log('自由节点信息:', freeTextBoxData)
  console.log('保存表单数据:', {
    mapName: saveForm.mapName,
    permission: saveForm.permission,
    alertEmails: saveForm.alertEmails,
    isDraft: isDraft.value // 新增草稿标识字段
  })
  
  // 关闭对话框
  saveDialogVisible.value = false
  
  // 重置表单和草稿状态
  saveForm.mapName = ''
  saveForm.permission = '个人'
  saveForm.alertEmails = ''
  isDraft.value = false
}

// 修改handleSaveCancel方法，重置草稿状态
const handleSaveCancel = () => {
  saveDialogVisible.value = false
  // 重置表单和草稿状态
  saveForm.mapName = ''
  saveForm.permission = '个人'
  saveForm.alertEmails = ''
  isDraft.value = false
}
const handleShowExport = () => {
  $emit('showExport')
}

// 监听�?
watch(isHandleLocalFile, (val) => {
  if (!val) {
    ElNotification.closeAll()
  }
})

watch(btnLit, () => {
  computeToolbarShow()
}, { deep: true })

// 方法
const computeToolbarShow = () => {
  if (!toolbarRef.value) return
  const windowWidth = window.innerWidth - 40
  const all = [...btnLit.value]
  let index = 1
  const loopCheck = () => {
    if (index > all.length) return done()
    horizontalList.value = all.slice(0, index)
    nextTick(() => {
      const width = toolbarRef.value.getBoundingClientRect().width
      if (width < windowWidth) {
        index++
        loopCheck()
      } else if (index > 0 && width > windowWidth) {
        index--
        horizontalList.value = all.slice(0, index)
        done()
      }
    })
  }
  const done = () => {
    verticalList.value = all.slice(index)
    showMoreBtn.value = verticalList.value.length > 0
  }
  loopCheck()
}

// 监听本地文件读写
const onWriteLocalFile = (content) => {
  clearTimeout(timer.value)
  if (fileHandle && isHandleLocalFile.value) {
    waitingWriteToLocalFile.value = true
  }
  timer.value = setTimeout(() => {
    writeLocalFile(content)
  }, 1000)
}

const onUnload = (e) => {
  if (waitingWriteToLocalFile.value) {
    const msg = '存在未保存的数据'
    e.returnValue = msg
    return msg
  }
}

// 加载本地文件�?
const loadFileTreeNode = async (node, resolve) => {
  try {
    let dirHandle
    if (node.level === 0) {
      dirHandle = await window.showDirectoryPicker()
      rootDirName.value = dirHandle.name
    } else {
      dirHandle = node.data.handle
    }
    const dirList = []
    const fileList = []
    for await (const [key, value] of dirHandle.entries()) {
      const isFile = value.kind === 'file'
      if (isFile && !/\.(smm|xmind|md|json)$/.test(value.name)) {
        continue
      }
      const enableEdit = isFile && /\.smm$/.test(value.name)
      const data = {
        id: key,
        name: value.name,
        type: value.kind,
        handle: value,
        leaf: isFile,
        enableEdit
      }
      if (isFile) {
        fileList.push(data)
      } else {
        dirList.push(data)
      }
    }
    resolve([...dirList, ...fileList])
  } catch (error) {
    console.log(error)
    fileTreeVisible.value = false
    resolve([])
    if (error.toString().includes('aborted')) {
      return
    }
    ElMessage.warning(t('toolbar.notSupportTip'))
  }
}

// 扫描本地文件�?
const openDirectory = () => {
  fileTreeVisible.value = false
  fileTreeExpand.value = true
  rootDirName.value = ''
  nextTick(() => {
    fileTreeVisible.value = true
  })
}

// 编辑指定文件
const editLocalFile = (data) => {
  if (data.handle) {
    fileHandle = data.handle
    readFile()
  }
}

// 导入指定文件
const importLocalFile = async (data) => {
  try {
    const file = await data.handle.getFile()
    // 这里需要通过父组件来处理导入，因为Import组件在模板中
    // 暂时使用事件总线来处�?   
     $emit('importFile', {
      raw: file,
      name: file.name
    })
  } catch (error) {
    console.log(error)
  }
}

// 打开本地文件
const openLocalFile = async () => {
  try {
    let [_fileHandle] = await window.showOpenFilePicker({
      types: [
        {
          description: '',
          accept: {
            'application/json': ['.smm']
          }
        }
      ],
      excludeAcceptAllOption: true,
      multiple: false
    })
    if (!_fileHandle) {
      return
    }
    fileHandle = _fileHandle
    if (fileHandle.kind === 'directory') {
      ElMessage.warning(t('toolbar.selectFileTip'))
      return
    }
    readFile()
  } catch (error) {
    console.log(error)
    if (error.toString().includes('aborted')) {
      return
    }
    ElMessage.warning(t('toolbar.notSupportTip'))
  }
}

// 读取本地文件
const readFile = async () => {
  let file = await fileHandle.getFile()
  let fileReader = new FileReader()
  fileReader.onload = async () => {
    store.setIsHandleLocalFile(true)
    setData(fileReader.result)
    ElNotification.closeAll()
    ElNotification({
      title: t('toolbar.tip'),
      message: `${t('toolbar.editingLocalFileTipFront')}${
        file.name
      }${t('toolbar.editingLocalFileTipEnd')}`,
      duration: 0,
      showClose: true
    })
  }
  fileReader.readAsText(file)
}

// 渲染读取的数�?
const setData = (str) => {
  try {
    let data = JSON.parse(str)
    if (typeof data !== 'object') {
      throw new Error(t('toolbar.fileContentError'))
    }
    if (data.root) {
      isFullDataFile.value = true
    } else {
      isFullDataFile.value = false
      data = {
        ...exampleData,
        root: data
      }
    }
    $emit('setData', data)
  } catch (error) {
    console.log(error)
    ElMessage.error(t('toolbar.fileOpenFailed'))
  }
}

// 写入本地文件
const writeLocalFile = async (content) => {
  if (!fileHandle || !isHandleLocalFile.value) {
    waitingWriteToLocalFile.value = false
    return
  }
  if (!isFullDataFile.value) {
    content = content.root
  }
  let string = JSON.stringify(content)
  const writable = await fileHandle.createWritable()
  await writable.write(string)
  await writable.close()
  waitingWriteToLocalFile.value = false
}

// 创建本地文件
const createNewLocalFile = async () => {
  await createLocalFile(exampleData)
}

// 另存�?
const saveLocalFile = async () => {
  let data = getData()
  await createLocalFile(data)
}

// 创建本地文件
const createLocalFile = async (content) => {
  try {
    let _fileHandle = await window.showSaveFilePicker({
      types: [
        {
          description: '',
          accept: { 'application/json': ['.smm'] }
        }
      ],
      suggestedName: t('toolbar.defaultFileName')
    })
    if (!_fileHandle) {
      return
    }
    const loading = ElLoading.service({
      lock: true,
      text: t('toolbar.creatingTip'),
      spinner: 'el-icon-loading',
      background: 'rgba(0, 0, 0, 0.7)'
    })
    fileHandle = _fileHandle
    store.setIsHandleLocalFile(true)
    isFullDataFile.value = true
    await writeLocalFile(content)
    await readFile()
    loading.close()
  } catch (error) {
    console.log(error)
    if (error.toString().includes('aborted')) {
      return
    }
    ElMessage.warning(t('toolbar.notSupportTip'))
  }
}

const onNodeNoteDblclick = (node, e) => {
  e.stopPropagation()
  $emit('showNodeNote', node)
}

// 生命周期钩子
onMounted(async() => {
  await nextTick()
  computeToolbarShow()
  computeToolbarShowThrottle.value = throttle(computeToolbarShow, 300)
  window.addEventListener('resize', computeToolbarShowThrottle.value)
  $on('lang_change', computeToolbarShowThrottle.value)
  window.addEventListener('beforeunload', onUnload)
  $on('node_note_dblclick', onNodeNoteDblclick)
  $on('write_local_file', onWriteLocalFile)
})

onBeforeUnmount(() => {
  $off('write_local_file', onWriteLocalFile)
  window.removeEventListener('resize', computeToolbarShowThrottle.value)
  $off('lang_change', computeToolbarShowThrottle.value)
  window.removeEventListener('beforeunload', onUnload)
  $off('node_note_dblclick', onNodeNoteDblclick)
})

// 在script setup中添加router实例
const router = useRouter()

// 新增返回列表方法
const handleBackToList = () => {
  router.back() // 路由回退一级
}
</script>

<style lang="less" scoped>
.toolbarContainer {
  &.isDark {
    .toolbar {
      color: hsla(0, 0%, 100%, 0.9);
      .toolbarBlock {
        background-color: #262a2e;

        .fileTreeBox {
          background-color: #262a2e;

          :deep(.el-tree) {
            background-color: #262a2e;

            &.el-tree--highlight-current {
              .el-tree-node.is-current > .el-tree-node__content {
                background-color: hsla(0, 0%, 100%, 0.05) !important;
              }
            }

            .el-tree-node:focus > .el-tree-node__content {
              background-color: hsla(0, 0%, 100%, 0.05) !important;
            }

            .el-tree-node__content:hover,
            .el-upload-list__item:hover {
              background-color: hsla(0, 0%, 100%, 0.02) !important;
            }
          }

          .fileTreeWrap {
            .customTreeNode {
              .treeNodeInfo {
                color: #fff;
              }

              .treeNodeBtnList {
                .el-button {
                  padding: 7px 5px;
                }
              }
            }
          }
        }
      }

      .toolbarBtn {
        .icon {
          background: transparent;
          border-color: transparent;
        }

        &:hover {
          &:not(.disabled) {
            .icon {
              background: hsla(0, 0%, 100%, 0.05);
            }
          }
        }

        &.disabled {
          color: #54595f;
        }
      }
    }
  }
  .toolbar {
    position: fixed;
    left: 50%;
    transform: translateX(-50%);
    top: 20px;
    width: max-content;
    display: flex;
    font-size: 12px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: rgba(26, 26, 26, 0.8);
    z-index: 2;

    .toolbarBlock {
      display: flex;
      background-color: #fff;
      padding: 10px 20px;
      border-radius: 6px;
      box-shadow: 0 2px 16px 0 rgba(0, 0, 0, 0.06);
      border: 1px solid rgba(0, 0, 0, 0.06);
      margin-right: 20px;
      flex-shrink: 0;
      position: relative;

      &:last-of-type {
        margin-right: 0;
      }

      .fileTreeBox {
        position: absolute;
        left: 0;
        top: 68px;
        width: 100%;
        height: 30px;
        background-color: #fff;
        padding: 12px 5px;
        padding-top: 0;
        display: flex;
        flex-direction: column;
        overflow: hidden;
        border-radius: 5px;
        min-width: 200px;
        box-shadow: 0 2px 16px 0 rgba(0, 0, 0, 0.06);

        &.expand {
          height: 300px;

          .fileTreeWrap {
            visibility: visible;
          }
        }

        .fileTreeToolbar {
          width: 100%;
          height: 30px;
          flex-shrink: 0;
          display: flex;
          align-items: center;
          justify-content: space-between;
          border-bottom: 1px solid #e9e9e9;
          margin-bottom: 12px;
          padding-left: 12px;

          .fileTreeName {
          }

          .fileTreeActionList {
            .btn {
              font-size: 18px;
              margin-left: 12px;
              cursor: pointer;
            }
          }
        }

        .fileTreeWrap {
          width: 100%;
          height: 100%;
          overflow: auto;
          visibility: hidden;

          .customTreeNode {
            flex: 1;
            display: flex;
            align-items: center;
            justify-content: space-between;
            font-size: 13px;
            padding-right: 5px;

            .treeNodeInfo {
              display: flex;
              align-items: center;

              .treeNodeIcon {
                margin-right: 5px;
                opacity: 0.7;
              }

              .treeNodeName {
                max-width: 200px;
                overflow: hidden;
                text-overflow: ellipsis;
                white-space: nowrap;
              }
            }

            .treeNodeBtnList {
              display: flex;
              align-items: center;
            }
          }
        }
      }
    }

    .toolbarBtn {
      display: flex;
      justify-content: center;
      flex-direction: column;
      cursor: pointer;
      margin-right: 20px;

      &:last-of-type {
        margin-right: 0;
      }

      &:hover {
        &:not(.disabled) {
          .icon {
            background: #f5f5f5;
          }
        }
      }

      &.active {
        .icon {
          background: #f5f5f5;
        }
      }

      &.disabled {
        color: #bcbcbc;
        cursor: not-allowed;
        pointer-events: none;
      }

      .icon {
        display: flex;
        height: 26px;
        background: #fff;
        border-radius: 4px;
        border: 1px solid #e9e9e9;
        justify-content: center;
        flex-direction: column;
        text-align: center;
        padding: 0 5px;
      }

      .text {
        margin-top: 3px;
      }
    }
  }
}
</style>
